import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		account: null,
		token: null,
		menu: {
			active: 'home',
			opens: []
		}
	},
	
	getters: {
		token: state => {
			//从缓存中取出token
			state.token = localStorage.getItem("account.token");
			return state.token;
		},
		
		account: state => {
			var acc = localStorage.getItem("account.account");
			if(acc != null) {
				state.account = JSON.parse(acc);
			}
			return state.account;
		},
		
		menu: state => {
			var name = localStorage.getItem("menu.active");
			if(name != null) {
				state.menu.active = name;
			}
			
			var openJson = localStorage.getItem("menu.opens");
			if(openJson != null) {
				state.menu.opens = JSON.parse(openJson);
			}
			
			return state.menu;
		}
	},
	
	mutations: {
		setAccount(state, account) {
			state.account = account;
			state.token = account.token;
			
			localStorage.setItem("account.account", JSON.stringify(account));
			localStorage.setItem("account.token", account.token);
		},
		
		clearAccount(state) {
			state.account = null;
			state.token = null;
			state.menu.active = null;
			state.menu.opens = [];
			
			localStorage.removeItem("account.account");
			localStorage.removeItem("account.token");
			
			localStorage.removeItem("menu.active");
			localStorage.removeItem("menu.opens");
			
			console.log("clear account");
		},
		
		setMenu(state, data) {
			console.log(data)
			if(data == null) {
				return;
			}
			if(data.active != null) {
				state.menu.active = data.active;
				localStorage.setItem("menu.active", data.active);
			}
			
			if(data.opens != null) {
				state.menu.opens = data.opens;
				localStorage.setItem("menu.opens", JSON.stringify(data.opens));
			}
		}
	}
})

export default store;